package cn.javabb.admin.controller.sys;

import cn.javabb.common.model.ResponseModel;
import cn.javabb.common.utils.BUtil;
import cn.javabb.common.utils.ListUtils;
import cn.javabb.core.base.BaseController;
import cn.javabb.core.constant.SysConstant;
import cn.javabb.core.entity.sys.MenuDO;
import cn.javabb.core.service.sys.MenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/admin/menu")
public class MenuAdminController extends BaseController {

    @Autowired
    private MenuService menuService;
    
    /**
     * 菜单列表页面
     * @author QINB
     * @param model
     * @return
     */
    @GetMapping("/list")
    public String toListPage(Model model) {
        return "admin/system/menu";
    }
    /**
     * 权限授权页面
     * @author QINB
     * @param model
     * @return
     */
    @GetMapping("/save")
    public String toSavePage(Model model) {
        List<MenuDO> menuList = menuService.listMenusByType(SysConstant.MENU_TYPE_MENU);
        model.addAttribute("menuList", menuList);
        return "admin/system/menuSave";
    }
    @ResponseBody
    @GetMapping("/treeSelect")
    public Object treeSelect(MenuDO menu){
        List<MenuDO> menuList = menuService.listMenusByType(SysConstant.MENU_TYPE_MENU);
        if(ListUtils.isNotEmpty(menuList)){
            return ResponseModel.Success(menuList);
        }
        return ResponseModel.Failure("查询异常");
    }
    /**
     * 权限资源管理
     * @param menu
     * @return
     */
    @ResponseBody
    @GetMapping("/tree")
    public Object tree(MenuDO menu){
        List<MenuDO> menuList = menuService.queryAll();
        if(ListUtils.isNotEmpty(menuList)){
            return ResponseModel.Success(menuList);
        }
        return ResponseModel.Failure("查询异常");
    }
    @ResponseBody
    @PostMapping("/")
    public Object save(MenuDO menu){
        int num;
        if(null == menu.getParentId()){
            menu.setParentId(0);
        }
        if(BUtil.isNull(menu.getId())){
            //insert
            menu.setState(1);
            num = menuService.insertSelective(menu);
        }else{
            //update
            num = menuService.updateSelective(menu);
        }
        if(num>0){
            return ResponseModel.Success("保存成功");
        }

        return ResponseModel.Failure("保存失败");
    }
    @ResponseBody
    @DeleteMapping("/{ids}")
    public Object delete(@PathVariable String ids){
        if(StringUtils.isBlank(ids)){
            return ResponseModel.Failure("参数错误");
        }
        if(menuService.delete(ids)){
            return ResponseModel.Success("删除成功");
        }
        return ResponseModel.Failure("删除失败");
    }
}
